<script setup>
    import reserveApi from "@/api/reserve.js";
    import courseApi from "@/api/course.js";
    import userApi from "@/api/user.js";
    import {ref, onMounted} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    //数据表格
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const reserveQuery = ref({
        courseId:'',
        userId:'',
        page:1,
        limit:10
    })

    const dateTimeRange = ref([])

    // 下拉框数据
    const courses = ref([])
    const users = ref([])

    const loadData = () =>{
        reserveApi.list(reserveQuery.value).then(result=>{
            if (result.code == 0){
                list.value = result.data.records
                total.value = result.data.total
            }
        })
    }
    
    // 加载课程数据
    const loadCourses = () => {
        courseApi.list({page: 1, limit: 1000}).then(result => {
            if (result.code == 0) {
                courses.value = result.data.records
            }
        })
    }
    
    // 加载用户数据
    const loadUsers = () => {
        userApi.list({page: 1, limit: 1000}).then(result => {
            if (result.code == 0) {
                users.value = result.data.records
            }
        })
    }

    onMounted(() => {
        loadData()
        loadCourses()
        loadUsers()
    })

    const onSearch = () =>{
        reserveQuery.value.page = 1
        reserveQuery.value.beginUpdateTime = null
        reserveQuery.value.endUpdateTime = null
        if (dateTimeRange.value && dateTimeRange.value.length == 2){
            reserveQuery.value.beginUpdateTime = dateTimeRange.value[0]
            reserveQuery.value.endUpdateTime = dateTimeRange.value[1]
        }
        loadData()
    }

    const reset = () =>{
        reserveQuery.value.courseId = ''
        reserveQuery.value.userId = ''
    }

    //根据ID删除
    const deleteById = (id) =>{
        ElMessageBox.confirm(
            '您确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                reserveApi.deleteById(id).then(result =>{
                    if (result.code == 0){
                        ElMessage.success(result.msg)
                        loadData()
                    }else {
                        ElMessage.error(result.msg)
                    }
                })
            })
    }

    //批量删除
    const ids = ref([])
    const handleSelectionChange = (rows) =>{
        console.log('多选',rows)
        ids.value = rows.map(row => row.id)
        console.log(ids.value)
    }
    const deleteAll = () =>{
        ElMessageBox.confirm(
            '您确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                reserveApi.deleteAll(ids.value).then(result =>{
                    if (result.code == 0){
                        ElMessage.success(result.msg)
                        loadData()
                    }else {
                        ElMessage.error(result.msg)
                    }
                })
            })
    }

    //添加、编辑
    const dialogFormVisible = ref(false)
    const reserve = ref({})
    const title = ref('')
    const showAddDialog = () =>{
        reserve.value = {}
        title.value = '添加预约'
        dialogFormVisible.value = true
    }

    const showUpdateDialog = (id) =>{
        // 检查预约状态
        const reserveItem = list.value.find(item => item.id === id)
        if (reserveItem && reserveItem.status === 0) {
            ElMessage.warning('该预约已被取消，无法编辑')
            return
        }
        
        title.value = '编辑预约'
        dialogFormVisible.value = true
        reserve.value = {}
        reserveApi.selectById(id).then(result =>{
            if (result.code == 0 ){
                reserve.value = result.data
            }
        })
    }

    const addOrUpdate = () =>{
        if (reserve.value.id){
            reserveApi.update(reserve.value).then(result =>{
                if (result.code == 0){
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false
                    loadData()
                }else {
                    ElMessage.error(result.msg)
                }
            })
        }else {
            reserveApi.add(reserve.value).then(result =>{
                if (result.code == 0){
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false
                    loadData()
                }else {
                    ElMessage.error(result.msg)
                }
            })
        }

    }

    // 取消预约
    const cancelReserve = (id) => {
        // 检查预约状态
        const reserve = list.value.find(item => item.id === id)
        if (reserve && reserve.status === 0) {
            ElMessage.warning('该预约已被取消，无法重复操作')
            return
        }
        
        ElMessageBox.confirm(
            '您确认要取消这个预约吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                reserveApi.cancelReserve(id).then(result => {
                    if (result.code == 0) {
                        ElMessage.success('预约已取消')
                        loadData()
                    } else {
                        ElMessage.error(result.msg)
                    }
                })
            })
    }

</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-button type="primary" @click="showAddDialog">添加</el-button>
                <el-button type="primary" @click="deleteAll">批量删除</el-button>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="课程">
                <el-select v-model="reserveQuery.courseId" placeholder="请选择课程" clearable style="width: 200px">
                    <el-option 
                        v-for="course in courses" 
                        :key="course.id" 
                        :label="course.name" 
                        :value="course.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="用户">
                <el-select v-model="reserveQuery.userId" placeholder="请选择用户" clearable style="width: 200px">
                    <el-option 
                        v-for="user in users" 
                        :key="user.id" 
                        :label="user.name" 
                        :value="user.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="更新时间" :label-width="100">
                <el-date-picker
                    clearable
                    v-model="dateTimeRange"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="danger" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="courseName" label="课程名称"/>
            <el-table-column prop="courseRoom" label="教室"/>
            <el-table-column prop="courseTime" label="课程时间" width="180px"/>
            <el-table-column prop="userName" label="用户姓名"/>
            <el-table-column prop="userPhone" label="用户电话"/>
            <el-table-column prop="status" label="状态" width="120px">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '已预约' : '已取消' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="预约时间" width="180px"/>
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="320px" fixed="right" label="操作">
                <template #default="{ row }">
                    <el-button 
                        size="small" 
                        type="primary" 
                        @click="showUpdateDialog(row.id)"
                        :disabled="row.status === 0"
                    >
                        编辑
                    </el-button>
                    <el-button 
                        size="small" 
                        type="warning" 
                        @click="cancelReserve(row.id)"
                        :disabled="row.status === 0"
                    >
                        取消预约
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="reserveQuery.page"
            v-model:page-size="reserveQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>

    <!--添加编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" :lock-scroll="false">
        <el-form :model="reserve">
            <el-form-item label="课程" :label-width="60">
                <el-select v-model="reserve.courseId" placeholder="请选择课程" style="width: 100%">
                    <el-option 
                        v-for="course in courses" 
                        :key="course.id" 
                        :label="course.name" 
                        :value="course.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="用户" :label-width="60">
                <el-select v-model="reserve.userId" placeholder="请选择用户" style="width: 100%">
                    <el-option 
                        v-for="user in users" 
                        :key="user.id" 
                        :label="user.name" 
                        :value="user.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style scoped lang="scss">
</style>
